package com.crearo.crgooglemap.online.view;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.crearo.crgooglemap.BaseActivity;
import com.crearo.crgooglemap.R;
import com.crearo.crgooglemap.online.present.OnlinePresent;
import com.crearo.crgooglemap.util.AnimationUtil;
import com.crearo.crgooglemap.util.CustomMapTileProvider;
import com.crearo.crgooglemap.util.GpsCorrect;
import com.crearo.crgooglemap.util.LatLngUtil;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationAvailability;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.places.GeoDataClient;
import com.google.android.gms.location.places.PlaceDetectionClient;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.Cap;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;

import java.util.List;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class OnlineActivity extends BaseActivity implements GoogleMap.OnCameraChangeListener,
        GoogleMap.OnMarkerDragListener, GoogleMap.OnMapClickListener, OnMapReadyCallback, IOnlineView,
        SeekBar.OnSeekBarChangeListener, View.OnClickListener, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener {

    private static final int LOCATE_INTERVAL = 3000;
    private LinearLayout ll_route, ll_circle, ll_square, ll_bubble, ll_offline,
            ll_level_add, ll_level_des, ll_level_control;
    private TextView tv_current_pi, tv_list_in_circle, tv_mode, tv_level;
    private LinearLayout ll_circle_console;
    private RelativeLayout rl_menu;
    private SeekBar sb_radius;
    private Circle circle;
    private OnlinePresent onlinePresent = new OnlinePresent(this);
    ;
    private GoogleMap mMap;
    private Polyline polyline;
    private Polygon polygon;
    private PolylineOptions polylineOptions;
    private boolean isConsoleShow = false, isMarkShow = false, isMenuShow = true, isOnline = true;
    private Marker marker0, marker1, marker2, marker3, marker4, marker_location;

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    private static final int REQUEST_CHECK_SETTINGS = 2;
    private GoogleApiClient mGoogleApiClient;
    private Location mLastLocation;
    private LocationRequest mLocationRequest;
    private boolean mLocationUpdateState;

    @Override
    protected void initDate(Bundle savedInstanceState) {
        fullScreen();
        hideBottomMenu(true);
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }
        createLocationRequest();
    }

    @Override
    protected void initView() {
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        tv_current_pi = findViewById(R.id.tv_current_pi);
        tv_mode = findViewById(R.id.tv_mode);
        tv_level = findViewById(R.id.tv_level);
        tv_list_in_circle = findViewById(R.id.tv_list_in_circle);
        ll_level_control = findViewById(R.id.ll_level_control);
        ll_level_add = findViewById(R.id.ll_level_add);
        ll_level_add.setOnClickListener(this);
        ll_level_des = findViewById(R.id.ll_level_des);
        ll_level_des.setOnClickListener(this);
        ll_route = findViewById(R.id.ll_route);
        ll_circle = findViewById(R.id.ll_circle);
        ll_bubble = findViewById(R.id.ll_bubble);
        ll_square = findViewById(R.id.ll_square);
        ll_offline = findViewById(R.id.ll_off);
        ll_route.setOnClickListener(this);
        ll_circle.setOnClickListener(this);
        ll_bubble.setOnClickListener(this);
        ll_square.setOnClickListener(this);
        ll_offline.setOnClickListener(this);
        sb_radius = findViewById(R.id.sb_radius);
        sb_radius.setOnSeekBarChangeListener(this);
        ll_circle_console = findViewById(R.id.ll_circle_console);
        rl_menu = findViewById(R.id.rl_menu);
        polylineOptions = new PolylineOptions().width(5).color(R.color.blue_range).geodesic(true);
    }

    @Override
    protected void onStart() {
        mGoogleApiClient.connect();
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    private void setUpMap() {
        if (ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]
                    {android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
            return;
        }
        mMap.setMyLocationEnabled(true);
        LocationAvailability locationAvailability =
                LocationServices.FusedLocationApi.getLocationAvailability(mGoogleApiClient);
        if (null != locationAvailability && locationAvailability.isLocationAvailable()) {
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            if (mLastLocation != null) {
                onlinePresent.default_point = new LatLng(mLastLocation.getLatitude(), mLastLocation
                        .getLongitude());
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(onlinePresent.default_point, 13));
            }
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setOnMapClickListener(this);
        mMap.setOnMarkerDragListener(this);
        mMap.setOnCameraChangeListener(this);
        addMarker();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
        }
        mMap.getUiSettings().setMyLocationButtonEnabled(true); // 右上角不显示定位图标
    }

    protected void startLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                    LOCATION_PERMISSION_REQUEST_CODE);
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(LOCATE_INTERVAL);
        mLocationRequest.setFastestInterval(LOCATE_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(mLocationRequest);
        PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
                        builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(@NonNull LocationSettingsResult result) {
                final Status status = result.getStatus();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        mLocationUpdateState = true;
                        startLocationUpdates();
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        try {
                            status.startResolutionForResult(OnlineActivity.this, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        break;
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CHECK_SETTINGS) {
            if (resultCode == RESULT_OK) {
                mLocationUpdateState = true;
                startLocationUpdates();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mGoogleApiClient.isConnected() && !mLocationUpdateState) {
            startLocationUpdates();
        }
    }

    private void addMarker() {
        MarkerOptions markerOption1 = new MarkerOptions().position(onlinePresent.point1).flat(true).draggable(true);
        MarkerOptions markerOption2 = new MarkerOptions().position(onlinePresent.point2).flat(true).draggable(true);
        MarkerOptions markerOption5 = new MarkerOptions().position(onlinePresent.point5).flat(true).draggable(true);
        MarkerOptions markerOption4 = new MarkerOptions().position(onlinePresent.point4).flat(true).draggable(true);
        mMap.addMarker(markerOption1);
        mMap.addMarker(markerOption2);
        mMap.addMarker(new MarkerOptions().position(onlinePresent.point3).title("单兵3"));
        mMap.addMarker(markerOption4);
        mMap.addMarker(markerOption5);
    }

    /**
     * 初始化多边形四个顶点
     */
    private void initSquare(List<LatLng> latLngs) {
        onlinePresent.initSquareDate();
        BitmapDescriptor bd = BitmapDescriptorFactory.fromResource(R.drawable.flag);
        BitmapDescriptor bd1 = BitmapDescriptorFactory.fromResource(R.drawable.no);
        marker1 = mMap.addMarker(new MarkerOptions().position(latLngs.get(0)).icon(bd1).draggable(true).flat(false));
        marker2 = mMap.addMarker(new MarkerOptions().position(latLngs.get(1)).icon(bd).title("A2").draggable(true).flat(true));
        marker3 = mMap.addMarker(new MarkerOptions().position(latLngs.get(2)).icon(bd1).draggable(true));
        marker4 = mMap.addMarker(new MarkerOptions().position(latLngs.get(3)).icon(bd).title("A4").draggable(true).flat(true));
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_online;
    }

    @Override
    public void drawLine(List<LatLng> latLngs) {
        if (polylineOptions == null || mMap == null) {
            return;
        }
        polylineOptions.addAll(latLngs);
        polyline = mMap.addPolyline(polylineOptions);
    }

    @Override
    public void drawCircle(LatLng latLng, double pi) {
        if (marker0 != null) marker0.remove();
        marker0 = mMap.addMarker(new MarkerOptions().position(latLng).
                icon(BitmapDescriptorFactory.fromResource(R.drawable.circlecenter)).draggable(true));
        CircleOptions circleOptions = new CircleOptions();
        circleOptions.center(latLng);
        circleOptions.fillColor(getResources().getColor(R.color.blue_range));
        circleOptions.clickable(true);
        circleOptions.strokeWidth(0.0f);
        circleOptions.radius(pi);
        circle = mMap.addCircle(circleOptions);
        circle.setStrokeColor(getResources().getColor(R.color.blue_range));
    }

    @Override
    public void drawSquare(List<LatLng> latLngs) {
        initSquare(latLngs);
        PolygonOptions rectOptions = new PolygonOptions()
                .add(latLngs.get(0), latLngs.get(1), latLngs.get(2), latLngs.get(3), latLngs.get(0))
                .strokeColor(getResources().getColor(R.color.blue_range))
                .strokeWidth(0.2f)
                .fillColor(getResources().getColor(R.color.blue_range));
        polygon = mMap.addPolygon(rectOptions);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_route:
                swipe(2);
                swipe(3);
                break;
            case R.id.ll_bubble:
                swipe(2);
                swipe(3);
                break;
            case R.id.ll_circle:
                int x = (int) (21 - onlinePresent.zoom);
                Log.i("x1x1x1", "x:" + x);
                doCircle(onlinePresent.default_point, onlinePresent.getCurrentPI());
                break;
            case R.id.ll_square:
                doSquare(onlinePresent.latLngs);
                break;
            case R.id.ll_off:
                doLineMode();
                break;
            case R.id.ll_level_add:
                mMap.animateCamera(CameraUpdateFactory.zoomIn());
                break;
            case R.id.ll_level_des:
                mMap.animateCamera(CameraUpdateFactory.zoomOut());
                break;
        }
    }

    private void doLineMode() {

        if (isOnline) {
            tv_mode.setText("在线");
            mMap.setMapType(mMap.MAP_TYPE_NONE);
            CustomMapTileProvider customMapTileProvider = new CustomMapTileProvider(getAssets(), this);
            mMap.addTileOverlay(new TileOverlayOptions().tileProvider(customMapTileProvider).zIndex(-1));
        } else {
            tv_mode.setText("离线");
            mMap.clear();
            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            addMarker();
        }
        isOnline = !isOnline;
    }

    private void doCircle(LatLng latLng, double pi) {
        if (circle != null) {
            circle.remove();
        }
        if (marker0 != null) marker0.remove();
        if (!isConsoleShow) {
            ll_circle_console.setVisibility(View.VISIBLE);
            AnimationUtil.Translate(this, ll_circle_console, AnimationUtil.IN_FROM_BOTTOM);
            sb_radius.setVisibility(View.VISIBLE);
            drawCircle(latLng, pi);
        } else {
            AnimationUtil.Translate(this, ll_circle_console, AnimationUtil.OUT_FROM_BOTTOM);
        }
        isConsoleShow = !isConsoleShow;
    }

    private void doSquare(List<LatLng> latLngs) {
        if (polygon != null) {
            polygon.remove();
        }
        swipe(3);
        if (!isConsoleShow) {
            sb_radius.setVisibility(View.GONE);
            ll_circle_console.setVisibility(View.VISIBLE);
            AnimationUtil.Translate(this, ll_circle_console, AnimationUtil.IN_FROM_BOTTOM);
            drawSquare(latLngs);
        } else {
            AnimationUtil.Translate(this, ll_circle_console, AnimationUtil.OUT_FROM_BOTTOM);
            sb_radius.setVisibility(View.VISIBLE);
        }
        isConsoleShow = !isConsoleShow;
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        onlinePresent.radius = onlinePresent.getCurrentPI() * i / 15;
        tv_current_pi.setText("当前半径：" + onlinePresent.radius);
        if (circle != null) {
            circle.setRadius(onlinePresent.radius);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                String x = onlinePresent.judgeOnClircle();
                subscriber.onNext(x);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(String s) {
                        tv_list_in_circle.setText("范围内的单兵有：" + s);
                    }
                });
    }

    private void swipe(int type) {
        switch (type) {
            case 1:
                break;
            case 2:
                if (circle != null) {
                    circle.remove();
                }
                if (isConsoleShow) {
                    AnimationUtil.Translate(this, ll_circle_console, AnimationUtil.OUT_FROM_BOTTOM);
                    isConsoleShow = false;
                }
                break;
            case 3:
                if (polygon != null) {
                    polygon.remove();
                }
                if (marker1 != null) marker1.remove();
                if (marker2 != null) marker2.remove();
                if (marker3 != null) marker3.remove();
                if (marker4 != null) marker4.remove();
                if (isConsoleShow) {
                    AnimationUtil.Translate(this, ll_circle_console, AnimationUtil.OUT_FROM_BOTTOM);
                    isConsoleShow = false;
                }
                break;
        }
    }

    @Override
    public void onMapClick(LatLng latLng) {

        if (isMenuShow) {
            isMenuShow = false;
            AnimationUtil.Translate(this, rl_menu, AnimationUtil.OUT_FROM_LEFT);
            AnimationUtil.Translate(this, ll_level_control, AnimationUtil.OUT_FROM_BOTTOM);
            if (isConsoleShow) {
                AnimationUtil.Translate(this, ll_circle_console, AnimationUtil.OUT_FROM_BOTTOM);
                isConsoleShow = false;
            }
        } else {
            isMenuShow = true;
            AnimationUtil.Translate(this, rl_menu, AnimationUtil.IN_FROM_LEFT);
            AnimationUtil.Translate(this, ll_level_control, AnimationUtil.IN_FROM_BOTTOM);
        }
    }

    @Override
    public void onMarkerDragStart(Marker marker) {

        if (marker.equals(marker2)) {
            onlinePresent.temp_position2 = onlinePresent.A2;
        }
        if (marker.equals(marker4)) {
            onlinePresent.temp_position4 = onlinePresent.A4;
        }
        onlinePresent.temp_position1 = onlinePresent.A1;
        onlinePresent.temp_position3 = onlinePresent.A3;
        drawShape(marker, polygon);
    }

    @Override
    public void onMarkerDrag(Marker marker) {
        drawShape(marker, polygon);
    }

    private void drawShape(Marker marker, Polygon polygon) {

        if (marker.equals(marker0)) {
            circle.setCenter(marker.getPosition());
        }
        if (marker.equals(marker2)) {
            if (marker.getPosition().latitude >= onlinePresent.A4.latitude
                    || marker.getPosition().longitude <= onlinePresent.A4.longitude) {
                return;
            }
            onlinePresent.A2 = marker.getPosition();
            onlinePresent.A1 = new LatLng(onlinePresent.A1.latitude, marker.getPosition().longitude);
            onlinePresent.A3 = new LatLng(marker.getPosition().latitude, onlinePresent.A3.longitude);
            onlinePresent.latLngs.set(0, onlinePresent.A1);
            onlinePresent.latLngs.set(1, onlinePresent.A2);
            onlinePresent.latLngs.set(2, onlinePresent.A3);
            polygon.setPoints(onlinePresent.latLngs);
        }
        if (marker.equals(marker4)) {
            if (marker.getPosition().longitude >= onlinePresent.A2.longitude
                    || marker.getPosition().latitude <= onlinePresent.A2.latitude) {
                return;
            }
            onlinePresent.A4 = marker.getPosition();
            onlinePresent.A1 = new LatLng(marker.getPosition().latitude, onlinePresent.A1.longitude);
            onlinePresent.A3 = new LatLng(onlinePresent.A3.latitude, marker.getPosition().longitude);
            onlinePresent.latLngs.set(0, onlinePresent.A1);
            onlinePresent.latLngs.set(2, onlinePresent.A3);
            onlinePresent.latLngs.set(3, onlinePresent.A4);
            polygon.setPoints(onlinePresent.latLngs);
        }
    }

    @Override
    public void onMarkerDragEnd(Marker marker) {
        judgeLegalSquare(marker);
        String x = "";
        if (marker.equals(marker0) && circle != null) {
            circle.setFillColor(getResources().getColor(R.color.blue_range));
            onlinePresent.default_point = marker.getPosition();
            x = onlinePresent.judgeOnClircle();
        }
        if ((marker.equals(marker2) || marker.equals(marker4)) && polygon != null) {
            polygon.setFillColor(getResources().getColor(R.color.blue_range));
            x = onlinePresent.judgeInSquare();
        }
        final String x1 = x;
        //Log.i("kokokoko","x1:"+x1);
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                subscriber.onNext(x1);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(String s) {
                        Log.i("danbing1", "s:" + s);
                        tv_list_in_circle.setText("范围内的单兵有：" + s);
                    }
                });
    }

    private void judgeLegalSquare(Marker marker) {

        if (marker.equals(marker2)) {
            if (marker.getPosition().latitude >= onlinePresent.A4.latitude ||
                    marker.getPosition().longitude <= onlinePresent.A4.longitude) {
                onlinePresent.A2 = onlinePresent.temp_position2;
                onlinePresent.A1 = onlinePresent.temp_position1;
                onlinePresent.A3 = onlinePresent.temp_position3;
                onlinePresent.latLngs.set(0, onlinePresent.A1);
                onlinePresent.latLngs.set(1, onlinePresent.A2);
                onlinePresent.latLngs.set(2, onlinePresent.A3);
                marker2.remove();
                marker2 = mMap.addMarker(new MarkerOptions().position(onlinePresent.latLngs.get(1)).
                        icon(BitmapDescriptorFactory.fromResource(R.drawable.flag)).
                        title("A2").draggable(true).flat(true));
                polygon.setPoints(onlinePresent.latLngs);
                return;
            }
        }
        if (marker.equals(marker4)) {
            if (marker.getPosition().longitude >= onlinePresent.A2.longitude ||
                    marker.getPosition().latitude <= onlinePresent.A2.latitude) {
                onlinePresent.A4 = onlinePresent.temp_position4;
                onlinePresent.A1 = onlinePresent.temp_position1;
                onlinePresent.A3 = onlinePresent.temp_position3;
                onlinePresent.latLngs.set(0, onlinePresent.A1);
                onlinePresent.latLngs.set(2, onlinePresent.A3);
                onlinePresent.latLngs.set(3, onlinePresent.A4);
                marker4.remove();
                marker4 = mMap.addMarker(new MarkerOptions().position(onlinePresent.latLngs.get(3)).
                        icon(BitmapDescriptorFactory.fromResource(R.drawable.flag)).
                        title("A4").draggable(true).flat(true));
                polygon.setPoints(onlinePresent.latLngs);
                return;
            }
        }
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        onlinePresent.zoom = cameraPosition.zoom;
        onlinePresent.default_point = cameraPosition.target;
        tv_level.setText((int) onlinePresent.zoom + "");
    }

    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;
        if (null == mLastLocation) {
            return;
        }
        //LatLng latLng=new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
        boolean flag = Math.abs(onlinePresent.default_point.latitude - mLastLocation.getLatitude()) > 0.01
                || Math.abs(onlinePresent.default_point.longitude - mLastLocation.getLatitude()) > 0.001;
        if (flag) {
            onlinePresent.latLngs.add(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()));
            onlinePresent.default_point = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
            Log.i("popopo", onlinePresent.default_point.latitude + " : " + onlinePresent.default_point.longitude);
            //drawLine(onlinePresent.latLngs);
            if(polyline!=null) {
                polyline.setPoints(onlinePresent.latLngs);
            }
        }
        placeMarkerOnMap(onlinePresent.default_point);
    }

    boolean isFirst = true;

    protected void placeMarkerOnMap(LatLng location) {
        if (mMap == null) {
            return;
        }
        if (isFirst) {
            drawLine(onlinePresent.latLngs);
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(onlinePresent.default_point, 16));
        }
        isFirst = false;
        if (marker_location != null) {
            marker_location.remove();
        }
        marker_location = mMap.addMarker(new MarkerOptions().position(onlinePresent.default_point)
                .draggable(false).flat(false));
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if (mLocationUpdateState) {
            startLocationUpdates();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        setUpMap();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
}

